//
//  HMHomeViewModel.swift
//  webo
//
//  Created by apple on 2016/11/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage
/*
 
 ***********MVC**************
 - vc
 - tableView   [HMStatus]
 - cell    HMStatus
 -------------------------------------------
 
 **********只是处理tableView 数据***********
 - vc   -------    HMHomeViewModel
 - tableView     获取视图模型的属性(模型数组[HMStatus])
 - cell    ---  HMStatus
 
 -------------------------------------------
 
 
 ********处理cell的viewmodel 和tableView [viewmodel]*******
 - vc   -------    HMHomeViewModel
 - tableView     获取视图模型的属性(模型数组[HMStatusCellViewModel])
 - cell    ---  HMStatusCellViewModel(HMStatus)
 
 */

class HMHomeViewModel: NSObject {
    
    lazy var viewmodelArray: [HMStatusViewModel] = [HMStatusViewModel]()
    
    func loadData(isPullUp: Bool, finished: @escaping (Bool,Int) -> ()){
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        
        if isPullUp {
            maxId = viewmodelArray.last?.status?.id ?? 0
            if maxId != 0 {
                maxId -= 1
            }
        }else{
            sinceId = viewmodelArray.first?.status?.id ?? 0
        }
//        //                         "max_id" : "\(maxId)",
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let parameter = ["access_token" : HMUserAccountViewModel.shared.access_token,
//                            "max_id" : "\(maxId)",
//
//                         "since_id" : "\(sinceId)"]
//        //        print(parameter)
//        
//        HMNetworkingTools.shared.request(method: .GET, urlString: urlString, parameter: parameter){(object,error) -> () in
//
//            if (error != nil) {
//                return
//            }
//            //        print(object)
//            let dic = object as! [String : Any]
//            
//            //阻塞
//            guard  let arr = dic["statuses"] as? [[String : Any]] else{
//                return
//            }
        HMStatusDAL.homeLoadData(sinceId: sinceId, maxId: maxId){ (arr) in
        
             if arr == nil{
                finished (false,0)
            return
            }
        
            var tempArray = [HMStatusViewModel]()
            
            //for循环解析数据
            for item in arr!{
                
                let s = HMStatusModel()
                
                let viewmodel = HMStatusViewModel()
                
                s.yy_modelSet(with: item)
                
                viewmodel.status = s
                
                //根据viewmodel来计算行高
                //1. 根据viewmodel获取cell
                let cell = self.loadCell(viewmodel: viewmodel)
                //2.给cell的viewmodel赋值
                cell.viewModel = viewmodel
                //3.强制提前刷新cell
                cell.layoutIfNeeded()
                //4.获取toolBar 最大Y值
                viewmodel.rowHeight = cell.uv_bottomTool.frame.maxY
                
                
                
                
                tempArray.append(viewmodel)
                
            }
            
            if isPullUp{
                self.viewmodelArray = self.viewmodelArray + tempArray
            }else{
                if tempArray.count == 20 {
                self.viewmodelArray = tempArray
                }else{
                self.viewmodelArray = tempArray + self.viewmodelArray
                }
            }
            //            finished(true,tempArray.count)
//            self.cacheStatusSingleImage(array: tempArray, finished: { (istrue, count) in
//                finished(istrue,count)
//            })
            finished(true,tempArray.count)
            
            
            self.cacheStatusSingleImage(array: tempArray, finished: finished)
        }
    }
    
    
    private func cacheStatusSingleImage(array: [HMStatusViewModel],finished:@escaping (Bool,Int) -> ()){
        if array.count == 0 {
            finished(true,0)
            return
        }
        let group = DispatchGroup()
        for statusV in array {
            if statusV.imgUrls?.count == 1{
                group.enter()
                let url = URL(string: statusV.imgUrls?.first?.wap360 ?? "")
                
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                  
                    let cell = self.loadCell(viewmodel: statusV)
                    //2.给cell的viewmodel赋值
                    cell.viewModel = statusV
                    //3.强制提前刷新cell
                    cell.layoutIfNeeded()
                    //4.获取toolBar 最大Y值
                    statusV.rowHeight = cell.uv_bottomTool.frame.maxY

                    group.leave()
                })
                
           }
        }
        group.notify(queue: DispatchQueue.main) {
            print("所有图片更新成功")
            finished(true,array.count)

        }
    }
    
    private func loadCell(viewmodel: HMStatusViewModel) -> HMStatusCell {
        
        return (viewmodel.status?.retweeted_status == nil) ?  orginalCell : tranmitCell
    }

    
//    private func loadCell(viewmodel: HMStatusViewModel) -> HMStatusCell {
//        if viewmodel.imgUrls?.count == 1{
//            let group = DispatchGroup()
//            group.enter()
//            let url = URL(string: viewmodel.imgUrls?.first?.wap360 ?? "")
//            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
//                group.leave()
//            })
//            group.notify(queue: DispatchQueue.main) {
//                print("所有图片更新成功")
//                return (viewmodel.status?.retweeted_status == nil) ?  orginalCell : tranmitCell
//                
//            }
//            
//        }
//        return (viewmodel.status?.retweeted_status == nil) ?  orginalCell : tranmitCell
//        
//    }
    

}

